package com.fas.web.controller.system;

import java.text.CollationKey;
import java.util.*;

import com.fas.common.core.domain.entity.SysDictData;
import com.fas.common.core.domain.entity.SysUser;
import com.fas.common.core.page.TableDataInfo;
import com.fas.common.utils.SecurityUtils;
import com.fas.system.domain.FasCooperationCompany;
import com.fas.system.domain.vo.DistributorVo;
import com.fas.system.domain.vo.MaintenanceUnitVo;
import com.fas.system.domain.vo.SysDeptVo;
import com.fas.system.mapper.FasCooperationCompanyMapper;
import com.fas.system.mapper.SysDeptMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.fas.common.annotation.Log;
import com.fas.common.constant.UserConstants;
import com.fas.common.core.controller.BaseController;
import com.fas.common.core.domain.AjaxResult;
import com.fas.common.core.domain.entity.SysDept;
import com.fas.common.enums.BusinessType;
import com.fas.common.utils.StringUtils;
import com.fas.system.service.ISysDeptService;

import javax.annotation.Resource;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@Api(value = "部门管理",tags = "部门管理")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private FasCooperationCompanyMapper fasCooperationCompanyMapper;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 获取部门列表
     */
    @GetMapping("/listVos")
    public AjaxResult listVos(SysDeptVo sysDeptVo)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysDept dept = deptService.selectDeptById(user.getDeptId());
        if ("0".equals(dept.getDeptType())) {//总公司
            SysDept query = new SysDept();
            query.setDeptId(dept.getDeptId());
            List<SysDeptVo> vos = deptMapper.selectDeptListVos(query);
            if (!CollectionUtils.isEmpty(vos)){
                SysDept query1 = new SysDept();
                query1.setParentId(dept.getDeptId());
                for (SysDeptVo vo : vos) {
                    List<SysDeptVo> disVos = deptMapper.selectDeptListVos(query1);
                    if (!CollectionUtils.isEmpty(disVos)) {
                        for (SysDeptVo disVo : disVos) {
                            SysDept query2 = new SysDept();
                            query2.setParentId(disVo.getDeptId());
                            List<SysDeptVo> maintainVos = deptMapper.selectDeptListVos(query2);
                            for (SysDeptVo maintainVo : maintainVos) {
                                // 通过deptId查询部门下的单位
                                List<FasCooperationCompany> fasCooperationCompanies = fasCooperationCompanyMapper.queryAll(new FasCooperationCompany(maintainVo.getDeptId().intValue()));
                                // 单位数组
                                List<SysDeptVo> companyList = new ArrayList<>();
                                for (FasCooperationCompany ff : fasCooperationCompanies) {
                                    SysDeptVo sysDeptVo1 = new SysDeptVo();
                                    sysDeptVo1.setDeptId(ff.getId().longValue());
                                    sysDeptVo1.setDeptName(ff.getCompanyName());
                                    sysDeptVo1.setParentId(vo.getDeptId());
                                    sysDeptVo1.setLatLud(ff.getLatLud());
                                    companyList.add(sysDeptVo1);
                                }
                                maintainVo.setChildren(companyList);
                            }
                            disVo.setChildren(maintainVos);
                        }
                    }
                    vo.setChildren(disVos);
                }
            }
            return AjaxResult.success(vos);
        }else if ("2".equals(dept.getDeptType())){//维保单位
            SysDept parentDept = deptService.selectDeptById(dept.getParentId());
            SysDeptVo parentVo = new SysDeptVo();
            BeanUtils.copyProperties(parentDept,parentVo);
            SysDeptVo vo = new SysDeptVo();
            BeanUtils.copyProperties(dept,vo);
            // 通过deptId查询部门下的单位
            List<FasCooperationCompany> fasCooperationCompanies = fasCooperationCompanyMapper.queryAll(new FasCooperationCompany(vo.getDeptId().intValue()));
            // 单位数组
            List<SysDeptVo> companyList = new ArrayList<>();
            for (FasCooperationCompany ff : fasCooperationCompanies) {
                SysDeptVo sysDeptVo1 = new SysDeptVo();
                sysDeptVo1.setDeptId(ff.getId().longValue());
                sysDeptVo1.setDeptName(ff.getCompanyName());
                sysDeptVo1.setParentId(vo.getDeptId());
                sysDeptVo1.setLatLud(ff.getLatLud());
                companyList.add(sysDeptVo1);
            }
            vo.setChildren(companyList);
            parentVo.setChildren(Collections.singletonList(vo));
            return AjaxResult.success(parentVo);
        }
        return null;
    }


    /**
     * 获取渠道商列表
     */
    @ApiOperation("渠道商列表")
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/listDistributors")
    public TableDataInfo listDistributors(@RequestParam(value = "condition",required = false) String condition)
    {
        SysDept dept = new SysDept();
        dept.setCondition(condition);
        startPage();
        List<DistributorVo> vos = deptService.selectDistributorVoList(dept);
        return getDataTable(vos);
    }

    /**
     * 获取维保单位列表
     */
    @ApiOperation("获取维保单位列表")
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/listMaintenanceUnits")
    public TableDataInfo listMaintenanceUnits(@RequestParam(value = "condition",required = false) String condition,
                                           @RequestParam(value = "distributorId",required = false)Long distributorId)
    {
        SysDept dept = new SysDept();
        dept.setCondition(condition);
        dept.setParentId(distributorId);
        startPage();
        List<MaintenanceUnitVo> depts = deptService.selectMaintenanceUnitVoList(dept);
        return getDataTable(depts);
    }


    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        Long deptId = deptService.genDeptId(dept);
        dept.setDeptId(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))  {
            return AjaxResult.error("新增 " + dept.getDeptName() + " 失败，名称已存在");
        }
        Integer ex = deptService.exitsDeptPhoneNumber(dept.getPhone());
        if (ex != null && ex > 0){
            return AjaxResult.error("新增 " + dept.getDeptName() + " 失败，电话号码已存在");
        }
        if(dept.getDeptType().equals("1")){
            dept.setParentId(getDeptId());
        }
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 新增渠道商
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addDistributor")
    public AjaxResult addDistributor(@RequestBody SysDept dept)
    {
        Long deptId = deptService.genDeptId(dept);
        dept.setDeptId(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增'" + dept.getDeptName() + "'失败，渠道商名称已存在");
        }
        Integer integer = deptService.exitsDeptPhoneNumber(dept.getPhone());
        if (integer != null && integer > 0){
            return AjaxResult.error("新增" + dept.getDeptName() + "'失败，电话号码已存在");
        }
        SysDept dept1 = new SysDept();
        dept.setDeptType("0");
        SysDept zonggongsi = deptMapper.selectDeptList(dept1).get(0);
        dept.setCreateBy(getUsername());
        dept.setDeptType("1");
        dept.setParentId(zonggongsi.getDeptId());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 新增维保单位
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addMaintain")
    public AjaxResult addMaintain(@RequestBody SysDept dept){
        Long deptId = deptService.genDeptId(dept);
        dept.setDeptId(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))){
            return AjaxResult.error("新增" + dept.getDeptName() + "'失败，维保单位名称已存在");
        }
        Integer integer = deptService.exitsDeptPhoneNumber(dept.getPhone());
        if (integer != null && integer > 0){
            return AjaxResult.error("新增" + dept.getDeptName() + "'失败，电话号码已存在");
        }
        dept.setCreateBy(getUsername());
        dept.setDeptType("2");
        dept.setStatus("0");
        dept.setParentId(dept.getParentId());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUniqueByDeptId(dept)))  {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId)) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }
}
